package com.xul.srb.oss.controller.api;

import com.xul.common.exception.BusinessException;
import com.xul.common.result.ResponseEnum;
import com.xul.common.result.Result;
import com.xul.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author xul
 * @create 2022-07-15 23:13
 */
@RestController
@Api(tags = "阿里云文件管理")
// @CrossOrigin
@RequestMapping("/api/oss/file")
public class FileController {

    @Resource
    private FileService fileService;

    @ApiOperation(("文件上传"))
    @PostMapping("/upload")
    public Result upload(@ApiParam(value = "文件", required = true)
                         @RequestParam("file") MultipartFile file,
                         @ApiParam(value = "模板", required = true)
                         @RequestParam("module") String module) {

        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String url = fileService.upLoad(inputStream, module, originalFilename);
            return Result.ok().data("url", url).message("文件上传成功");
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }

    }

    @ApiOperation("oss上文件的删除")
    @DeleteMapping("/remove")
    public Result remove(@ApiParam(value = "文件的url", required = true) @RequestParam("url") String url) {
        fileService.removeByUrl(url);
        return Result.ok().message("文件删除成功");
    }

}
